<template>
  <div id="app">
    <!-- 路由视图（首页缓存） -->
    <router-view v-slot="{ Component }">
      <keep-alive include="home">
        <component :is="Component" />
      </keep-alive>
    </router-view>

    <!-- 底部 Tabbar（按路由 meta 控制显示） -->
    <Tabbar v-if="showTabbar" default-color="#ccc" active-color="#fff" route>
      <TabbarItem name="home">首页</TabbarItem>
      <TabbarItem name="follow">关注</TabbarItem>
      <TabbarItem>
        <template #default>
          <button @click="handleAddClick" class="add-btn">
            <Icon name="add" color="#000" size="12" />
          </button>
        </template>
      </TabbarItem>
      <TabbarItem name="message">消息</TabbarItem>
      <TabbarItem name="my">我的</TabbarItem>
    </Tabbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, provide, inject, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserIDStore } from '@/stores/UserID'
import { showDialog } from './utils/dialog'
import { useUserStore } from '@/stores/userStatus'
const userStore = useUserStore()
import Icon from '@/components/Common/Icon/index.vue'

// 异步组件
const Tabbar = defineAsyncComponent(() => import('@/components/Common/Tabbar/index.vue'))
const TabbarItem = defineAsyncComponent(() => import('@/components/Common/TabbarItem/index.vue'))

// ========== 路由相关 ==========
const route = useRoute()
const router = useRouter()

const showTabbar = computed(() => route.meta.showTabbar)

const handleAddClick = () => {
  router.push({ name: 'uploadVideo' })
}

// ========== 用户交互状态（用于解除视频静音限制）==========
const USER_INTERACTED_KEY = 'userInteracted'
const userInteracted = ref(localStorage.getItem(USER_INTERACTED_KEY) === 'true')
provide('userInteracted', userInteracted)

// 设置用户已交互（保存状态）
const setUserInteracted = () => {
  userInteracted.value = true
  localStorage.setItem(USER_INTERACTED_KEY, 'true')
}

// ========== Socket 相关 ==========
const socket = inject('socket')
const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId

// 绑定用户身份到 Socket
const bindSocketIdentity = () => {
  if (userId && socket) {
    socket.emit('login', userId)
  }
}

// 显示“登录提示”对话框（仅当未交互过时）
// 显示“登录提示”对话框
const showLoginPrompt = () => {
  if (!userInteracted.value) {
    showDialog({
      message: '登录后可观看更多视频',
      confirmText: '确定',
      cancelText: '取消',
      showCancel: true,
    }).then(() => {
      // 用户点击“确定” → 打开登录弹窗
      userStore.openLoginModal()
      setUserInteracted()
    }).catch(() => {
      // 用户点击“取消”或关闭 → 仅标记已交互，不打开登录
      setUserInteracted()
    })
  }
}

// 清理函数（避免重复监听）
let hasBoundReconnect = false

onMounted(() => {
  // 1. 自动绑定用户身份
  bindSocketIdentity()

  // 2. 监听重连事件（只绑定一次）
  if (socket && !hasBoundReconnect) {
    socket.on('connect', bindSocketIdentity)
    hasBoundReconnect = true
  }

  // 3. 立即尝试显示登录提示（用于触发用户交互）
  showLoginPrompt()
})

onUnmounted(() => {
  if (socket && hasBoundReconnect) {
    socket.off('connect', bindSocketIdentity)
  }
})
</script>

<style scoped></style>